package com.jbm;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.rsa.cmbVerifyTools;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONBuilder;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by root on 18-6-12.
 */
public class UPHttpHandler implements com.sun.net.httpserver.HttpHandler
{
	protected static Logger logger = LoggerFactory.getLogger(UPHttpHandler.class);

	public UPHttpHandler()
	{
	}

	public static String BuildUPRequest(String content, String sequence,String wy_code)
	{
		JsonObject request = new JsonObject();

		request.addProperty("j_type","uprequest");
		request.addProperty("content",content);
		request.addProperty("sequence",sequence);
		request.addProperty("wy_code",wy_code);

		return request.toString();
	}

	@Override
	public void handle(HttpExchange exchange)
	{
//			String response = "{\"id\":1,\"name\":\"java\",\"ide\":\"eclipse\"}";

		try
		{

			SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"Method:"+exchange.getRequestMethod());


			Headers headers = exchange.getRequestHeaders();

			for ( Headers.Entry<String, List<String>> entry :headers.entrySet())
			{
				String key = entry.getKey();
				List<String> value = entry.getValue();

				String values = "|";

				for ( String str : value)
				{
					values += str;
					values += "|";
				}

				SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"Header:key="+key+"values"+values);
			}

			byte[] bytes = new byte[0];
			bytes = new byte[exchange.getRequestBody().available()];
//			exchange.getRequestBody().read(bytes);

//			String boday = new String(bytes, Charset.forName("UTF-8"));

			Map<String, Object> parameters = (Map<String, Object>)exchange.getAttribute("parameters");
			InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(),"utf-8");
			BufferedReader br = new BufferedReader(isr);

			String query = br.readLine();

//			SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"Body:%d %s",bytes.length, query);

			SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"URI:"+exchange.getRequestURI().toString());

			JsonObject request = new JsonObject();

			if (query != null)
			{
				String pairs[] = query.split("[&]");

				for (String pair : pairs)
				{
					String param[] = pair.split("[=]");

					String key = "";
					String value = "";
					if (param.length > 0)
					{
						key = URLDecoder.decode(param[0],
								System.getProperty("file.encoding"));
					}

					if (param.length > 1)
					{
						value = URLDecoder.decode(param[1],
								System.getProperty("file.encoding"));
					}
					request.addProperty(key,value);
					SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"Param:key=%s value=%s",key,value);
				}
			}

			int code = 500;
			String response = null;

			P2PDialog p2pdialog = new P2PDialog(10);
			p2pdialog.Born(5, 6000);
			synchronized (BridgeHnadler.b_server_ca_mutex)
			{
				ConnectAgent ca = BridgeHnadler.b_server_ca.get("shengning");

				if ( ca != null )
				{
					p2pdialog.Bind_IoSession(ca.getM_iosession());

					HttpHandler.m_dialogqueue.Add(p2pdialog);

					String uprequest = BuildUPRequest(request.toString(), p2pdialog.GetLifeName().toString(), "shengning");

					ca.Send(uprequest);

					response = (String) p2pdialog.Get();

					JsonParser parser = new JsonParser();
					JsonObject resp = (JsonObject) parser.parse(response);
					code = resp.get("code").getAsInt();
				} else if ( GDHandler.db_pool != null )
				{
					code = 500;
/*
					Connection conn = (Connection) GDHandler.db_pool.take();

					Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
*/
				}else
					code = 500;
			}

			exchange.sendResponseHeaders(code, 0);
			OutputStream os = exchange.getResponseBody();
			os.close();
		}catch (IOException ie) {

			logger.info(ie.getMessage());

		} catch (Exception e) {

			logger.info(e.getMessage());
		}
	}
}
